package xyz.lwm.lazycat.beans;

import lombok.AllArgsConstructor;
import xyz.lwm.lazycat.annotation.SettingPrefix;
import xyz.lwm.lazycat.setting.Setting;
import xyz.lwm.lazycat.utility.BeanUtil;
import xyz.lwm.lazycat.utility.It;

/**
 * 映射 setting 属性到 bean
 *
 * @author lwm
 */
@AllArgsConstructor
public class BeanPostProcessorForSetting implements BeanPostProcessor {

    private final BeanDesignRegistry registry;

    @Override
    public Object processBeforeInitialization(Object bean, String beanName) throws BeansException {
        BeanDesign<?> design = registry.getDesign(beanName);
        It.of(design.getAnnotations().getAnnotation(SettingPrefix.class))
                .let(SettingPrefix::value)
                .let(s -> Setting.get().forPath(s))
                .let(setting -> setting.toBean(design.getType()))
                .also(obj -> BeanUtil.copyProperties(obj, bean));
        return bean;
    }

}
